Util தொகுதி என்றால் என்ன?
Util தொகுதி என்பது பொதுவான பணிகளுக்கான பயன்பாட்டு செயல்பாடுகளின் தொகுப்பை வழங்கும் ஒரு core Node.js தொகுதியாகும்.
இது Node.js டெவலப்பர்களுக்கான ஒரு Swiss Army knife போன்றது, இது போன்ற தீர்வுகளை வழங்குகிறது:
பொதுவான பயன்பாட்டு நிகழ்வுகள்
Placeholders உடன் சரங்களை வடிவமைத்தல்
சர வடிவமைப்பு மற்றும் பதிலீடு
பிழைத்திருத்தத்திற்கான பொருள்களை ஆய்வு செய்தல்
பொருள் ஆய்வு மற்றும் பிரதிநிதித்துவம்
Callbacks மற்றும் Promises இடையே மாற்றுதல்
அசின்க்ரோனஸ் குறியீடு மாற்றம்
வகை சோதனை மற்றும் சரிபார்ப்பு
தரவு வகை சரிபார்ப்பு
கைவிடப்பட்ட எச்சரிக்கைகளை கையாளுதல்
API கைவிடல் மேலாண்மை
பிழைத்திருத்தம் மற்றும் பதிவு செய்தல்
பிழைத்திருத்தம் மற்றும் பதிவு உத்திகள்
முக்கிய நன்மைகள்
குறிப்பு:
Util தொகுதியில் உள்ள சில செயல்பாடுகள் Node.js தானே உள் பயன்பாட்டிற்காக வடிவமைக்கப்பட்டுள்ளன, ஆனால் பல Node.js பயன்பாடுகளை உருவாக்கும் டெவலப்பர்களுக்கு மதிப்புமிக்க கருவிகளாகும்.
தொகுதி Node.js உடன் சேர்க்கப்பட்டுள்ளது, எனவே நிறுவல் தேவையில்லை.
Util உடன் தொடங்குதல்
Util தொகுதியிலிருந்து பல பயன்பாடுகளை செயல்பாட்டில் நிரூபிக்கும் ஒரு நடைமுறை எடுத்துக்காட்டு இங்கே:
அடிப்படை பயன்பாடு எடுத்துக்காட்டு
const util = require('util');
const fs = require('fs');
// Convert callback-based fs.readFile to Promise-based
const readFile = util.promisify(fs.readFile);
// Format strings with placeholders
const greeting = util.format('Hello, %s! Today is %s', 'Developer', new Date().toDateString());
console.log(greeting);
// Inspect an object with custom options
const obj = {
name: 'Test',
nested: { a: 1, b: [2, 3] },
fn: function() { return 'test'; }
};
console.log(util.inspect(obj, { colors: true, depth: 2 }));
// Use debug logging
const debug = util.debuglog('app');
debug('This will only show if NODE_DEBUG=app');
// Example of using promisify with async/await
async function readConfig() {
try {
const data = await readFile('package.json', 'utf8');
console.log('Package name:', JSON.parse(data).name);
} catch (err) {
console.error('Error reading config:', err);
}
}
readConfig();
இறக்குமதி செய்தல் மற்றும் அமைப்பு
உங்கள் தொகுதி அமைப்பு மற்றும் தேவைகளைப் பொறுத்து Util தொகுதியை பல வழிகளில் இறக்குமதி செய்யலாம்:
CommonJS (Node.js இயல்புநிலை)
// Import the entire module
const util = require('util');
// Import specific functions using destructuring
const { promisify, inspect, format } = require('util');
// Using strict mode (recommended)
const assert = require('assert').strict;
// For TypeScript users
// import * as util from 'util';
// import { promisify, inspect } from 'util';
ES Modules (Node.js 12+)
// Default import
import util from 'util';
// Named imports
import { promisify, inspect } from 'util';
// Rename imports
import { promisify as pify } from 'util';
// Dynamic import (Node.js 14+)
const { promisify } = await import('util');
// Using with TypeScript types
// import * as util from 'util';
// import type { InspectOptions } from 'util';
சிறந்த நடைமுறை:
சிறந்த tree-shaking மற்றும் சிறிய bundles க்கு, உங்களுக்குத் தேவையான செயல்பாடுகளை மட்டுமே destructuring இறக்குமதிகளை விரும்புங்கள்.
Util தொகுதி மிகவும் பெரியது, மற்றும் நீங்கள் பொதுவாக அதன் செயல்பாட்டின் ஒரு சிறிய துணைக்குழுவை மட்டுமே பயன்படுத்துகிறீர்கள்.
சரம் வடிவமைத்தல் மற்றும் ஆய்வு
Util தொகுதி சரங்களை வடிவமைப்பதற்கும் பொருள்களை ஆய்வு செய்வதற்கும் சக்திவாய்ந்த கருவிகளை வழங்குகிறது, அவை குறிப்பாக பதிவு மற்றும் பிழைத்திருத்தத்திற்கு பயனுள்ளதாக இருக்கும்.
util.format(format[, ...args])
முதல் வாதத்தை printf போன்ற வடிவ சரமாகப் பயன்படுத்தி ஒரு வடிவமைக்கப்பட்ட சரத்தை வழங்குகிறது.
இது console.log() போன்றது, ஆனால் அதை அச்சிடுவதற்குப் பதிலாக வடிவமைக்கப்பட்ட சரத்தை வழங்குகிறது.
வடிவம் குறிப்பிடிகள்:
| குறிப்பிடி | விளக்கம் |
|---|---|
| %s | சரம் |
| %d | எண் (முழு எண் மற்றும் float இரண்டும்) |
| %i | முழு எண் |
| %f | Floating point மதிப்பு |
| %j | JSON (வாதம் வட்ட மேற்கோள்களைக் கொண்டிருந்தால் '[Circular]' உடன் மாற்றப்படும்) |
| %o | பொருள் (பொருளை ஆய்வு செய்யவும்) |
| %O | பொருள் (முழு விவரத்துடன் பொருளை ஆய்வு செய்யவும்) |
| %% | ஒற்றை சதவீத அடையாளம் ('%') |
const util = require('util');
// Basic formatting
const formatted = util.format('Hello, %s!', 'World');
console.log(formatted); // 'Hello, World!'
// Multiple placeholders
const multiFormatted = util.format(
'My name is %s. I am %d years old and I love %s.',
'Kai',
30,
'Node.js'
);
console.log(multiFormatted);
// 'My name is Kai. I am 30 years old and I love Node.js.'
// Available specifiers
const specifiers = util.format(
'String: %s, Number: %d, JSON: %j, Character: %c',
'hello',
42,
{ name: 'Object' },
65 // ASCII code for 'A'
);
console.log(specifiers);
// Extra arguments are concatenated with spaces
const extra = util.format('Hello', 'World', 'from', 'Node.js');
console.log(extra); // 'Hello World from Node.js'
util.inspect(object[, options])
பிழைத்திருத்தத்திற்கு பயனுள்ள ஒரு பொருளின் சரம் பிரதிநிதித்துவத்தை வழங்குகிறது.
பொருள்களை கன்சோலுக்கு அச்சிடுவதற்கு Node.js உள் முறையில் இதைப் பயன்படுத்துகிறது.
பொதுவான பயன்பாட்டு நிகழ்வுகள்:
- சிக்கலான பொருள்களை பிழைத்திருத்தம் செய்தல்
- மனித-படிக்கக்கூடிய பொருள் பிரதிநிதித்துவங்களை உருவாக்குதல்
- வட்ட மேற்கோள்களைக் கொண்ட பொருள்களை பதிவு செய்தல்
- பதிவுகளில் பொருள் காட்சியை தனிப்பயனாக்குதல்
பொதுவான விருப்பங்கள்:
| விருப்பம் | விளக்கம் | இயல்புநிலை |
|---|---|---|
| showHidden | கணக்கிட முடியாத பண்புகளைக் காட்டு | false |
| depth | மீண்டும் செய்ய வேண்டிய நிலைகளின் எண்ணிக்கை | 2, null for unlimited |
| colors | ANSI வண்ண குறியீடுகளைச் சேர்க்கவும் | false |
| customInspect | தனிப்பயன் ஆய்வு செயல்பாடுகளைப் பயன்படுத்தவும் | true |
| showProxy | Proxy விவரங்களைக் காட்டு | false |
| maxArrayLength | சேர்க்க வேண்டிய வரிசை உறுப்புகளின் அதிகபட்ச எண்ணிக்கை | 100 |
| breakLength | பொருள் விசைகளை உடைக்க வேண்டிய நீளம் | 60 |
| compact | புதிய வரிகளில் பண்புகளை உடைக்கவும் | true for arrays, false for objects |
| sorted | பண்புகளை வரிசைப்படுத்தவும் | false, true for alphabetical, function for custom sort |
const util = require('util');
// Basic usage
const obj = {
name: 'John',
age: 30,
hobbies: ['reading', 'coding'],
address: {
city: 'New York',
country: 'USA'
},
toString() {
return `${this.name}, ${this.age}`;
}
};
// Default inspection
console.log(util.inspect(obj));
// Custom options
console.log(util.inspect(obj, {
colors: true, // Add ANSI color codes
depth: 0, // Only inspect the first level
showHidden: true, // Show non-enumerable properties
compact: false, // Don't format objects on a single line
showProxy: true, // Show proxy details
maxArrayLength: 3, // Limit array elements displayed
breakLength: 50, // Line break after 50 characters
sorted: true // Sort object properties alphabetically
}));
// Circular references
const circular = { name: 'Circular' };
circular.self = circular;
console.log(util.inspect(circular));
util.inspect.custom
பொருள் ஆய்வை தனிப்பயனாக்க பயன்படுத்தப்படும் சின்னம்.
இது பொருள்கள் ஆய்வு செய்யப்படும் போது அவற்றின் சொந்த சரம் பிரதிநிதித்துவத்தை வரையறுக்க அனுமதிக்கிறது.
சிறந்த நடைமுறைகள்:
const util = require('util');
// Class with custom inspection
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
this._private = 'hidden information';
}
// Custom inspect method
[util.inspect.custom](depth, options) {
return `Person(${this.name}, ${this.age})`;
}
}
const kai = new Person('Kai', 30);
// Custom inspection is used
console.log(util.inspect(kai)); // Person(Kai, 30)
// Directly using console.log also uses custom inspection
console.log(kai); // Person(Kai, 30)
Promises மற்றும் Async பயன்பாடுகள்
Node.js இன் Util தொகுதி அசின்க்ரோனஸ் குறியீட்டுடன் பணிபுரிவதற்கு பல பயன்பாடுகளை வழங்குகிறது, callback-அடிப்படையிலான மற்றும் Promise-அடிப்படையிலான APIகளுடன் பணிபுரிவதை எளிதாக்குகிறது.
util.promisify(original)
Node.js callback முறையைப் பின்பற்றும் callback-அடிப்படையிலான செயல்பாட்டை Promise ஐ வழங்கும் செயல்பாட்டிற்கு மாற்றுகிறது.
இது callbacks ஐப் பயன்படுத்தும் பழைய Node.js APIகளுடன் பணிபுரிய பயனுள்ளதாக இருக்கிறது.
util.promisify எப்போது பயன்படுத்த வேண்டும்:
- callbacks ஐப் பயன்படுத்தும் பழைய Node.js APIகளுடன் பணிபுரிதல்
- callback-அடிப்படையிலான நூலகங்களை Promises ஐப் பயன்படுத்த மாற்றுதல்
- callbacks ஐ அகற்றுவதன் மூலம் async/await குறியீட்டை எளிதாக்குதல்
- Node.js callback முறையைப் பின்பற்றும் செயல்பாடுகளுடன் பணிபுரிதல் (error-first, single result)
வரம்புகள்:
- Node.js callback முறையைப் பின்பற்றும் செயல்பாடுகளுடன் மட்டுமே வேலை செய்கிறது: (err, value) => {}
- callback இல் பல மதிப்புகளை வழங்கும் செயல்பாடுகளுடன் வேலை செய்யாது
- மிகவும் சிக்கலான APIகளுக்கு தனிப்பயன் promisification தேவைப்படலாம்
const util = require('util');
const fs = require('fs');
// Convert fs.readFile from callback-based to Promise-based
const readFilePromise = util.promisify(fs.readFile);
// Now we can use it with async/await or Promise chaining
async function readFileExample() {
try {
// Using the promisified function
const data = await readFilePromise('package.json', 'utf8');
console.log('File content:', data.substring(0, 100) + '...');
// Error handling with try/catch
return 'File read successfully';
} catch (err) {
console.error('Error reading file:', err.message);
return 'Error reading file';
}
}
readFileExample().then(result => {
console.log('Result:', result);
});
util.callbackify(original)
Promise ஐ வழங்கும் செயல்பாட்டை Node.js callback முறையைப் பின்பற்றும் செயல்பாட்டிற்கு மாற்றுகிறது.
இது callback-அடிப்படையிலான APIகளுடன் பணிபுரிய பயனுள்ளதாக இருக்கிறது, அவை callback செயல்பாடுகளை எதிர்பார்க்கின்றன.
util.callbackify எப்போது பயன்படுத்த வேண்டும்:
- Promise-அடிப்படையிலான குறியீட்டை callback-அடிப்படையிலான APIகளுடன் ஒருங்கிணைத்தல்
- நூலகங்களில் பின்னோக்கி இணக்கத்தன்மையை பராமரித்தல்
- Node.js-பாணி callbacks எதிர்பார்க்கும் APIகளுடன் பணிபுரிதல்
- callbacks இலிருந்து Promises க்கு படிப்படியாக இடம்பெயர்தல்
சிறந்த நடைமுறைகள்:
const util = require('util');
// A Promise-based function
async function fetchUserData(id) {
if (!id) {
throw new Error('ID is required');
}
// Simulate API request
return {
id,
name: `User ${id}`,
email: `user${id}@example.com`
};
}
// Convert to callback-based
const fetchUserDataCallback = util.callbackify(fetchUserData);
// Using the callback-based function
fetchUserDataCallback(1, (err, user) => {
if (err) {
console.error('Error:', err);
return;
}
console.log('User data:', user);
});
// Error handling
fetchUserDataCallback(null, (err, user) => {
if (err) {
console.error('Error occurred:', err.message);
return;
}
console.log('User data:', user); // This won't execute
});
util.promisify.custom
promisification நடத்தையை தனிப்பயனாக்க சின்னம். ஒரு செயல்பாடு promisified செய்யப்படும் போது ஒரு தனிப்பயன் செயல்படுத்தலை வழங்க இது உங்களை அனுமதிக்கிறது.
தனிப்பயன் promisificationக்கான பயன்பாட்டு நிகழ்வுகள்:
- நிலையான callback முறையைப் பின்பற்றாத செயல்பாடுகள்
- callback இல் பல மதிப்புகளை வழங்கும் APIகள்
- தனிப்பயன் பிழை கையாளுதல் அல்லது முடிவுகளின் மாற்றம்
- குறிப்பிட்ட பயன்பாட்டு நிகழ்வுகளுக்கு செயல்திறனை மேம்படுத்துதல்
- promisification போது கூடுதல் செயல்பாட்டைச் சேர்த்தல்
const util = require('util');
// Function with custom promisification
function doSomething(options, callback) {
callback(null, 'regular result');
}
// Define custom promisification
doSomething[util.promisify.custom] = (options) => {
return Promise.resolve('custom promisified result');
};
// Use the custom promisification
const promisified = util.promisify(doSomething);
// Compare the results
async function compareResults() {
// Original function with callback
doSomething({}, (err, result) => {
console.log('Callback result:', result);
});
// Custom promisified function
const customResult = await promisified({});
console.log('Promisified result:', customResult);
}
compareResults();
வகை சோதனை பயன்பாடுகள்
Util தொகுதி JavaScript இன் typeof ஆபரேட்டரை விட மிகவும் நம்பகமான விரிவான வகை சோதனை பயன்பாடுகளை வழங்குகிறது, குறிப்பாக உள்ளமைக்கப்பட்ட பொருள்கள் மற்றும் Node.js-குறிப்பிட்ட வகைகளுக்கு.
ஏன் util.types பயன்படுத்த வேண்டும்?
const util = require('util');
// Example values
const values = [
'string',
123,
true,
Symbol('symbol'),
{ key: 'value' },
[1, 2, 3],
null,
undefined,
() => {},
BigInt(123),
new Date(),
/regex/,
Buffer.from('buffer'),
new Error('error')
];
// Check types for each value
values.forEach(value => {
console.log(`Value: ${util.inspect(value)}`);
console.log(`- isArray: ${util.types.isArrayBuffer(value)}`);
console.log(`- isDate: ${util.types.isDate(value)}`);
console.log(`- isRegExp: ${util.types.isRegExp(value)}`);
console.log(`- isNativeError: ${util.types.isNativeError(value)}`);
console.log(`- isPromise: ${util.types.isPromise(value)}`);
console.log(`- isPrimitive: ${util.isPrimitive(value)}`);
console.log(`- isString: ${util.isString(value)}`);
console.log(`- isNumber: ${util.isNumber(value)}`);
console.log(`- isBoolean: ${util.isBoolean(value)}`);
console.log(`- isSymbol: ${util.types.isSymbol(value)}`);
console.log(`- isNull: ${value === null}`);
console.log(`- isUndefined: ${value === undefined}`);
console.log(`- isFunction: ${util.types.isFunction(value)}`);
console.log(`- isBuffer: ${Buffer.isBuffer(value)}`);
console.log('---');
});
குறிப்பு:
util இல் உள்ள பல வகை-சோதனை செயல்பாடுகள் util.types அல்லது JavaScript இன் உள்ளமைக்கப்பட்ட வகை சோதனை முறைகள் போன்ற Array.isArray() க்கு ஆதரவாக கைவிடப்பட்டுள்ளன.
util.types
util.types பல்வேறு JavaScript வகைகள் மற்றும் Node.js-குறிப்பிட்ட பொருள்களுக்கான வகை சோதனை செயல்பாடுகளை வழங்குகிறது:
const util = require('util');
// JavaScript built-in types
console.log('util.types.isDate(new Date()):',
util.types.isDate(new Date()));
console.log('util.types.isRegExp(/test/):',
util.types.isRegExp(/test/));
console.log('util.types.isPromise(Promise.resolve()):',
util.types.isPromise(Promise.resolve()));
// Node.js-specific types
console.log('util.types.isArrayBuffer(new ArrayBuffer(0)):',
util.types.isArrayBuffer(new ArrayBuffer(0)));
console.log('util.types.isSharedArrayBuffer(new SharedArrayBuffer(0)):',
util.types.isSharedArrayBuffer(new SharedArrayBuffer(0)));
console.log('util.types.isUint8Array(new Uint8Array()):',
util.types.isUint8Array(new Uint8Array()));
// More advanced types
console.log('util.types.isProxy(new Proxy({}, {})):',
util.types.isProxy(new Proxy({}, {})));
console.log('util.types.isExternal(Requiring C++ binding):',
'Not demonstrated in this example');
கைவிடல் பயன்பாடுகள்
Node.js உங்கள் குறியீடு தளத்தை உருவாக்குவதற்கும் பின்னோக்கி இணக்கத்தன்மையை பராமரிப்பதற்கும் உதவ API கைவிடல்களை நிர்வகிக்க பயன்பாடுகளை வழங்குகிறது.
கைவிடல் உத்தி:
util.deprecate(fn, msg[, code])
ஒரு செயல்பாட்டை கைவிடப்பட்டதாகக் குறிக்கிறது, அது அழைக்கப்படும் போது ஒரு எச்சரிக்கையை வெளியிடுகிறது.
const util = require('util');
// Original function
function oldFunction(x, y) {
return x + y;
}
// Deprecate the function
const deprecatedFunction = util.deprecate(
oldFunction,
'oldFunction() is deprecated. Use newFunction() instead.',
'DEP0001'
);
// New function
function newFunction(x, y) {
return x + y;
}
// Using the deprecated function will show a warning
console.log('Result:', deprecatedFunction(5, 10));
// Using the new function
console.log('Result:', newFunction(5, 10));
கைவிடல் எச்சரிக்கைகளை நிர்வகித்தல்
நீங்கள் சூழல் மாறிகள் பயன்படுத்தி கைவிடல் எச்சரிக்கைகளின் காட்சியை கட்டுப்படுத்தலாம்:
# Show all deprecation warnings
NODE_OPTIONS='--trace-deprecation'
# Show only the first occurrence of each deprecation
NODE_OPTIONS='--no-deprecation'
# Silence all deprecation warnings
NODE_OPTIONS='--no-warnings'
# Turn deprecation warnings into exceptions
NODE_OPTIONS='--throw-deprecation'
பிழைத்திருத்தம் மற்றும் வளர்ச்சி பயன்பாடுகள்
Node.js பிழைத்திருத்தத்திற்கும் வளர்ச்சிக்கும் உதவ பல பயன்பாடுகளை வழங்குகிறது, சிக்கல்களை கண்டறிவதையும் பயன்பாட்டு நடத்தையைப் புரிந்துகொள்வதையும் எளிதாக்குகிறது.
util.debuglog(section)
NODE_DEBUG சூழல் மாறியின் அடிப்படையில் debug செய்திகளை stderr க்கு நிபந்தனையுடன் எழுதும் ஒரு செயல்பாட்டை உருவாக்குகிறது.
இது முழு-அம்ச பதிவு நூலகங்களுக்கு ஒரு இலகுவான மாற்று.
Debug பதிவுக்கான சிறந்த நடைமுறைகள்:
எடுத்துக்காட்டு பயன்பாடு:
// Enable debug logging for specific modules
// NODE_DEBUG=app,db node your-app.js
// In your application
const debugApp = util.debuglog('app');
const debugDB = util.debuglog('db');
// These will only log when 'app' is in NODE_DEBUG
debugApp('Application started with config: %j', config);
// These will only log when 'db' is in NODE_DEBUG
debugDB('Connected to database: %s', connectionString);
// Enable all debug logs (not recommended in production)
// NODE_DEBUG=* node your-app.js
const util = require('util');
// Create debug loggers for different sections
const debugApp = util.debuglog('app');
const debugDB = util.debuglog('db');
const debugAuth = util.debuglog('auth');
// These messages only appear when NODE_DEBUG includes 'app'
debugApp('Application starting...');
debugApp('Configuration loaded from %j', { source: 'config.json' });
// These messages only appear when NODE_DEBUG includes 'db'
debugDB('Connected to database');
debugDB('Query executed: %s', 'SELECT * FROM users');
// These messages only appear when NODE_DEBUG includes 'auth'
debugAuth('User authenticated: %s', 'john.doe');
// To see these messages, run your app with:
// NODE_DEBUG=app,db node your-app.js
console.log('Application running normally (this always shows)');
சுருக்கம்
Node.js Util தொகுதி Node.js டெவலப்பர்களுக்கான ஒரு சக்திவாய்ந்த மற்றும் பல்துறை கருவி பெட்டியாகும்:
சரம் வடிவமைத்தல்
util.format() மற்றும் வடிவம் குறிப்பிடிகள்
பொருள் ஆய்வு
util.inspect() மற்றும் தனிப்பயன் ஆய்வு
Async மாற்றங்கள்
util.promisify() மற்றும் util.callbackify()
வகை சோதனை
util.types மற்றும் வகை சரிபார்ப்பு செயல்பாடுகள்
கைவிடல் மேலாண்மை
util.deprecate() மற்றும் கைவிடல் உத்திகள்
Debug பதிவு
util.debuglog() மற்றும் நிபந்தனை பதிவு
இந்த பயன்பாடுகளைப் புரிந்துகொண்டு பயன்படுத்துவதன் மூலம், நீங்கள் மிகவும் பராமரிக்கக்கூடிய, பிழைத்திருத்தம் செய்யக்கூடிய மற்றும் செயல்திறன் மிக்க Node.js பயன்பாடுகளை எழுதலாம்.